extends Area2D
class_name EnemyHurtBoxComponent

@export var health_component: EnemyHealthComponent
var audio_hit = AudioStreamPlayer2D.new() # 受击音效
var idle_frame_num = 0
var is_die = false

func _ready() -> void:
	add_child(audio_hit)
	health_component.die.connect(on_die)
	
func _physics_process(_delta):
	# 移除不必要的伤害显示代码，避免重复显示
	pass

func enemy_hurt(_weapon, damage, is_critical: bool = false, damage_color = Color.RED):
	if is_die:
		return
	
	# 检查是否处于无敌状态
	if owner.has_method("is_invincible_state") and owner.is_invincible_state():
		# 无敌状态下不应用灼烧效果
		return
	
	on_hit(damage, is_critical, damage_color)
	audio_hit.play(0.17)
	# 检查是否有灼烧效果需要应用
	_check_burn_effect()
	
## 子弹击中
## 根据暴击率计算是否伤害乘积
func on_hit(hit_num, is_critical = false, damage_color = Color.RED):
	## 获取buff节点
	var nodes = get_tree().get_nodes_in_group("reward")
	var temp_hurt = 0
	for node in nodes:
		if node.connect_beforeAtk:
			var num = node.call("beforeAtk", self, hit_num)
			temp_hurt += num
	hit_num += temp_hurt
	
	## 计算暴击
	var final_damage = hit_num
	
	## 约到两位小数，然后根据是否暴击来显示效果，具体都在health_component
	final_damage = snapped(final_damage, 0.01)
	health_component.damage(final_damage, damage_color, is_critical)
	for node in nodes:
		if node.connect_afterAtk:
			node.call("afterAtk", self, final_damage)

## 检查并应用灼烧效果
func _check_burn_effect() -> void:
	# 检查玩家是否有灼烧技能
	if not Utils.player or not Utils.player.buff_manager:
		return
		
	# 获取灼烧技能等级
	var burn_skill_level = 0
	for skill in SkillManager.current_skills:
		if skill.get_string("name") == "灼烧":
			burn_skill_level = skill.get_integer("level")
			break
	
	if burn_skill_level > 0:
		# 创建灼烧buff
		var burn_damage = burn_skill_level * 0.5
		if Utils.player.buff_manager.has_buff("死神之书"):
			burn_damage += Utils.get_player_stats_value("max_mp")
		var burn_buff = BuffFactory.create_enemy_burn_buff(burn_damage, 3.0, 5)
		
		# 添加到敌人的buff管理器
		if health_component.buff_manager:
			health_component.buff_manager.add_buff(burn_buff, Utils.player)

func on_die() -> void:
	is_die = true
